import { AbstractSeeder } from '../abstract';
import { Prisma, PrismaClient } from '../../../src/generated/prisma';
import { DICT_DATA } from './dict.data';

export default class DictSeed extends AbstractSeeder {
  name = 'Dict' as const;
  data = DICT_DATA;

  async exec(tx: Prisma.TransactionClient): Promise<void> {
    for (const dict of this.data) {
      const { code, name, description, isSystem, status } = dict;
      const savedDict = await tx.sysDict.upsert({
        where: { code },
        update: { name, description, isSystem, status },
        create: { code, name, description, isSystem, status },
      });

      for (const item of dict.items) {
        const { value, label, status } = item;
        await tx.sysDictItem.upsert({
          where: { dictId_value: { dictId: savedDict.id, value } },
          update: { label, status },
          create: { dictId: savedDict.id, label, value, status },
        });
      }
    }
  }
}

if (require.main === module) {
  const prisma = new PrismaClient();
  new DictSeed()
    .run(prisma)
    .catch(e => {
      console.error(e)
      process.exit(1)
    })
    .finally(() => prisma.$disconnect());
}

